﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

using KorbeRTR.Models;

namespace KorbeRTR
{
    public partial class FormLogin : Form
    {
        public FormLogin()
        {
            InitializeComponent();
        }

        private List<User> list ;

        private void FormLogin_Load(object sender, EventArgs e)
        {
            //读取数据库
            list = User.ListAll();
         
            cbxUserName.DataSource = list;
            cbxUserName.DisplayMember = "UserName";
            cbxUserName.ValueMember = "Id";

        }

        /// <summary>
        /// 用户名密码和数据库比对正确后提示标志
        /// </summary>
        public bool logInOk = false;
        /// <summary>
        /// 确定
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnOK_Click(object sender, EventArgs e)
        {
            string uName = (cbxUserName.SelectedItem as User).UserName;          
            string uPwd = txtPwd.Text.Trim();

            if (string.IsNullOrEmpty(uPwd))
            {
                MessageBox.Show("密码不能为空!", "登录提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
                txtPwd.Focus();
                return;
            }

            foreach (var item in list)
            {

                if (item.UserName != uName) continue;
           

                if (item.Password != uPwd)
                {
                    MessageBox.Show("密码不正确,请重新输入!", "登录提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    txtPwd.Focus();
                }
                else
                {
                    Global.GetInstance().CurrentUser = item;
                    Global.LoginFlag = true;
                    logInOk = true;
                    this.Close();
                }

                break;
            }





        }

        /// <summary>
        /// 退出
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnCancel_Click(object sender, EventArgs e)
        {
            Close();
        }

        //回车当确认
        private void txtPwd_KeyPress(object sender, KeyPressEventArgs e)
        {
            if(e.KeyChar ==13)
            {
                btnOK_Click(sender, e);
            }
        }


        //private static FormLogin formLogin = null;

        //public static FormLogin CreateInstance()
        //{
        //    if (formLogin == null || formLogin.IsDisposed)
        //        formLogin = new FormLogin();
        //    return formLogin;
        //}
    }
}
